package com.example.service.impl;

import com.example.common.Result;
import com.example.dto.OperationLogQueryDTO;
import com.example.entity.OperationLog;
import com.example.mapper.OperationLogMapper;
import com.example.service.OperationLogService;
import com.example.vo.OperationLogDetailVO;
import com.example.vo.OperationLogVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 操作日志服务实现类
 */
@Service
public class OperationLogServiceImpl implements OperationLogService {
    
    @Autowired
    private OperationLogMapper operationLogMapper;
    
    private static final DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
    
    @Override
    public void recordLog(OperationLog operationLog) {
        try {
            if (operationLog.getCreateTime() == null) {
                operationLog.setCreateTime(LocalDateTime.now());
            }
            if (operationLog.getDeleted() == null) {
                operationLog.setDeleted(0);
            }
            operationLogMapper.insert(operationLog);
        } catch (Exception e) {
            // 记录日志失败不应该影响业务流程，只记录错误
            System.err.println("记录操作日志失败: " + e.getMessage());
        }
    }
    
    @Override
    public Result<Map<String, Object>> getOperationLogs(OperationLogQueryDTO queryDTO) {
        try {
            int offset = (queryDTO.getPage() - 1) * queryDTO.getSize();
            
            // 查询数据
            List<OperationLog> logs = operationLogMapper.selectPage(
                offset, queryDTO.getSize(),
                queryDTO.getUsername(), queryDTO.getModule(),
                queryDTO.getOperationType(), queryDTO.getStatus(),
                queryDTO.getStartTime(), queryDTO.getEndTime(),
                queryDTO.getIpAddress()
            );
            
            // 查询总数
            long total = operationLogMapper.selectCount(
                queryDTO.getUsername(), queryDTO.getModule(),
                queryDTO.getOperationType(), queryDTO.getStatus(),
                queryDTO.getStartTime(), queryDTO.getEndTime(),
                queryDTO.getIpAddress()
            );
            
            // 转换为VO
            List<OperationLogVO> logVOs = logs.stream().map(this::convertToVO).collect(Collectors.toList());
            
            Map<String, Object> result = new HashMap<>();
            result.put("list", logVOs);
            result.put("total", total);
            result.put("page", queryDTO.getPage());
            result.put("size", queryDTO.getSize());
            result.put("pages", (total + queryDTO.getSize() - 1) / queryDTO.getSize());
            
            return Result.success(result);
        } catch (Exception e) {
            return Result.error("查询操作日志失败：" + e.getMessage());
        }
    }
    
    @Override
    public Result<OperationLogDetailVO> getOperationLogDetail(Long id) {
        try {
            OperationLog operationLog = operationLogMapper.selectById(id);
            if (operationLog == null) {
                return Result.error("操作日志不存在");
            }
            
            OperationLogDetailVO detailVO = new OperationLogDetailVO();
            BeanUtils.copyProperties(operationLog, detailVO);
            
            return Result.success(detailVO);
        } catch (Exception e) {
            return Result.error("查询操作日志详情失败：" + e.getMessage());
        }
    }
    
    @Override
    public Result<Void> deleteOperationLog(Long id) {
        try {
            int result = operationLogMapper.deleteById(id);
            if (result > 0) {
                return Result.success();
            } else {
                return Result.error("删除失败，日志不存在");
            }
        } catch (Exception e) {
            return Result.error("删除操作日志失败：" + e.getMessage());
        }
    }
    
    @Override
    public Result<Void> batchDeleteOperationLogs(List<Long> ids) {
        try {
            if (ids == null || ids.isEmpty()) {
                return Result.error("请选择要删除的日志");
            }
            
            int result = operationLogMapper.deleteByIds(ids);
            if (result > 0) {
                return Result.success();
            } else {
                return Result.error("删除失败");
            }
        } catch (Exception e) {
            return Result.error("批量删除操作日志失败：" + e.getMessage());
        }
    }
    
    @Override
    public Result<List<OperationLogVO>> getUserOperationLogs(Long userId, Integer limit) {
        try {
            List<OperationLog> logs = operationLogMapper.selectByUserId(userId, limit);
            List<OperationLogVO> logVOs = logs.stream().map(this::convertToVO).collect(Collectors.toList());
            return Result.success(logVOs);
        } catch (Exception e) {
            return Result.error("查询用户操作日志失败：" + e.getMessage());
        }
    }
    
    @Override
    public Result<List<OperationLogVO>> getModuleOperationLogs(String module, Integer limit) {
        try {
            List<OperationLog> logs = operationLogMapper.selectByModule(module, limit);
            List<OperationLogVO> logVOs = logs.stream().map(this::convertToVO).collect(Collectors.toList());
            return Result.success(logVOs);
        } catch (Exception e) {
            return Result.error("查询模块操作日志失败：" + e.getMessage());
        }
    }
    
    @Override
    public Result<List<OperationLogVO>> getFailureLogs(LocalDateTime startTime, LocalDateTime endTime, Integer limit) {
        try {
            List<OperationLog> logs = operationLogMapper.selectFailureLogs(startTime, endTime, limit);
            List<OperationLogVO> logVOs = logs.stream().map(this::convertToVO).collect(Collectors.toList());
            return Result.success(logVOs);
        } catch (Exception e) {
            return Result.error("查询失败日志失败：" + e.getMessage());
        }
    }
    
    @Override
    public Result<Map<String, Object>> getOperationStatistics(LocalDateTime startTime, LocalDateTime endTime) {
        try {
            Map<String, Object> statistics = new HashMap<>();
            
            // 模块统计
            List<Map<String, Object>> moduleStats = operationLogMapper.selectModuleStatistics(startTime, endTime);
            statistics.put("moduleStats", moduleStats);
            
            // 操作类型统计
            List<Map<String, Object>> operationTypeStats = operationLogMapper.selectOperationTypeStatistics(startTime, endTime);
            statistics.put("operationTypeStats", operationTypeStats);
            
            return Result.success(statistics);
        } catch (Exception e) {
            return Result.error("获取操作统计失败：" + e.getMessage());
        }
    }
    
    @Override
    public Result<String> exportOperationLogs(OperationLogQueryDTO queryDTO) {
        // TODO: 实现导出功能
        return Result.error("导出功能暂未实现");
    }
    
    @Override
    public Result<Integer> cleanHistoryLogs(Integer days) {
        try {
            LocalDateTime beforeTime = LocalDateTime.now().minusDays(days);
            int deletedCount = operationLogMapper.deleteBeforeTime(beforeTime);
            return Result.success(deletedCount);
        } catch (Exception e) {
            return Result.error("清理历史日志失败：" + e.getMessage());
        }
    }
    
    @Override
    public Result<Map<String, Object>> getTodayStatistics() {
        try {
            LocalDateTime startOfDay = LocalDateTime.now().withHour(0).withMinute(0).withSecond(0);
            LocalDateTime endOfDay = LocalDateTime.now().withHour(23).withMinute(59).withSecond(59);
            
            return getOperationStatistics(startOfDay, endOfDay);
        } catch (Exception e) {
            return Result.error("获取今日统计失败：" + e.getMessage());
        }
    }
    
    @Override
    public Result<Map<String, Object>> getUserOperationTrend(Long userId, Integer days) {
        // TODO: 实现用户操作趋势分析
        return Result.error("用户操作趋势分析功能暂未实现");
    }
    
    /**
     * 转换为VO对象
     */
    private OperationLogVO convertToVO(OperationLog operationLog) {
        OperationLogVO vo = new OperationLogVO();
        BeanUtils.copyProperties(operationLog, vo);
        
        // 格式化时间
        if (operationLog.getCreateTime() != null) {
            vo.setCreateTimeStr(operationLog.getCreateTime().format(DATE_TIME_FORMATTER));
        }
        
        // 设置描述信息
        vo.setOperationTypeDesc(getOperationTypeDesc(operationLog.getOperationType()));
        vo.setStatusDesc(getStatusDesc(operationLog.getStatus()));
        
        return vo;
    }
    
    /**
     * 获取操作类型描述
     */
    private String getOperationTypeDesc(String operationType) {
        if (operationType == null) return "";
        
        switch (operationType) {
            case "CREATE": return "新增";
            case "UPDATE": return "修改";
            case "DELETE": return "删除";
            case "QUERY": return "查询";
            case "LOGIN": return "登录";
            case "LOGOUT": return "登出";
            case "EXPORT": return "导出";
            case "IMPORT": return "导入";
            default: return operationType;
        }
    }
    
    /**
     * 获取状态描述
     */
    private String getStatusDesc(String status) {
        if (status == null) return "";
        
        switch (status) {
            case "SUCCESS": return "成功";
            case "FAILURE": return "失败";
            default: return status;
        }
    }
}
